package edu.ynu.onlinesqltool.control;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.ynu.onlinesqltool.action.*;

public class ControlServlet extends HttpServlet {
	public void init(ServletConfig config) throws ServletException{
		super.init(config);
	}
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		doPost(req, resp);
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		String action = req.getParameter("action");
		IAction iAction = null;
		if(action != null){
			if(action.equals("showtable")){
				iAction = new ShowTableAction();
				iAction.execute(req, resp);
			}
			if(action.equals("describetable")){
				iAction = new DescribeTableAction();
				iAction.execute(req, resp);
			}
			if(action.equals("execute")){
				String sql = req.getParameter("sql");
				String firstWord = sql.substring(0, sql.indexOf(" ")).toLowerCase();
				if(firstWord.equals("select")||firstWord.equals("show")||firstWord.equals("describe")){
					iAction = new QueryAction();
					iAction.execute(req, resp);
				}
				if(firstWord.equals("update")||firstWord.equals("insert")||firstWord.equals("delete")){
					iAction = new UpdateAction();
					iAction.execute(req, resp);
				}
				if(firstWord.equals("create")||firstWord.equals("drop")){
					iAction = new CreateAndDropAction();
					iAction.execute(req, resp);
				}
			}
		}
	}
}
